// Database related
'use strict';

var mysql   = require('mysql')
  , connection = mysql.createConnection({
      host     : "127.0.0.1",
      user     : "root",
      password : "aaa",
      database : "weixin"
    });

connection.connect(function(err) {
  // connected! (unless `err` is set)
  if (err) {
    console.log("DB conn error...");
  } else {
    console.log("DB connected :)");
  }
});


function handleDisconnect(connection) {
  connection.on('error', function(err) {
    if (!err.fatal) {
      return;
    }

    if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
      throw err;
    }

    console.log('Re-connecting lost connection: ' + err.stack);

    connection = mysql.createConnection(connection.config);
    handleDisconnect(connection);
    connection.connect();
  });
}

handleDisconnect(connection);

exports.getTranslationsByDate = function (data, callback) {
  var where ="";
  if(data[4]!=0){
    where = "where `"+data[3]+"`='"+data[4]+"'";
  }
  var tb = data[0];
  var size = data[2];
  var start = (data[1] - 1)*size;

  var query = connection.query('SELECT * FROM '+tb+' '+where+' limit '+start+','+size+' ;', '', callback);
  console.log(query.sql);
};
